package com.singleton.demo02;

import java.util.HashMap;
import java.util.Map;

/**
 * 登记式单例: 目的是为了解决懒汉式和饿汉式单例类均不可继承(构造子私有)的缺点而设计的.
 */
public class RegSingleton {
    private static Map<String, RegSingleton> regMap = new HashMap<>();

    static {
        RegSingleton regSingleton = new RegSingleton();
        regMap.put(regSingleton.getClass().getName(), regSingleton);
    }

    /**
     * 受保护的默认构造器
     */
    protected RegSingleton(){}

    public static RegSingleton getInstance(String name){
        if (null == name) {
             name = "com.singleton.demo02.RegSingleton";
        }

        if (regMap.get(name) == null) {
            try {
                regMap.put(name, (RegSingleton) Class.forName(name).newInstance());
            }catch (Exception e){
                System.out.println("Error...");
            }
        }

        return regMap.get(name);
    }

}
